﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

/*
 场景题 3：数据库连接池
 场景描述：
     你的应用程序需要管理数据库连接。为了避免频繁地创建和销毁数据库连接，你决定实现一个连接池。连接池应该是一个单例，以确保所有数据库连接都通过这个单一的连接池进行管理。
 练习要求：
     实现一个单例模式的数据库连接池类。
     提供方法来获取和释放数据库连接。
     确保连接池在整个应用程序中只有一个实例。
 */
namespace CS_BEGINNER_TO_PROFICIENT.DesignPatterns.CreationMode.SingletonPattern.Practice
{
    public class ConnectionPool
    {
        private static readonly Lazy<ConnectionPool> _instance = new Lazy<ConnectionPool>(() => new ConnectionPool());
        private readonly ConcurrentBag<SqlConnection> _connections;
        private readonly string _connectionString;

        private ConnectionPool()
        {
            _connections = new ConcurrentBag<SqlConnection>();
            _connectionString = "Server = localhost; Database = CS; uid = root; pwd = 123456; Trusted_Connection = False";
            InitializePool();
        }

        private static ConnectionPool Instance => _instance.Value;

        private void InitializePool()
        {
            for (int i = 0; i < 10; i++)
            {
                _connections.Add(CreateConnection());
            }
        }

        private SqlConnection CreateConnection()
        {
            return new SqlConnection(_connectionString);
        }

        private SqlConnection GetConnection()
        {
            if (_connections.TryTake(out var connection))
            {
                return connection;
            }

            return CreateConnection();
        }

        public void ReleaseConnection(SqlConnection connection)
        {
            _connections.Add(connection);
        }
    }
}
